<template>
  <div id="main">
    <div class="topContent">
      <div class="top-logo">
        <div class="sysName">
          <img :src="topDescribe.logoSrc" alt />
          <span class="divider">|</span>
          <label v-if="notYueGang">设备资产管理系统</label>
          <ul v-else style="margin-left: 20px">
            <li class="title-top" @click="goInfoManage">工程信息化管理平台</li>
            <li class="title-bottom">设备资产管理系统</li>
          </ul>
        </div>
        <div class="top-center">
          <div
            ref="topTitle"
            class="tool-btn"
            :class="{ itemActive: isActive == item.meta }"
            @click="gotoIndex(item)"
            v-for="(item, index) in tooBtn"
            :key="index"
          >
            <!-- @click="gotoIndex()"> -->
            <i :class="item.icon"></i>
            <label>{{ item.name }}</label>
            <el-badge
              ref="badgeRefs"
              v-if="item.meta == 'undo' && badgeValue != 0"
              :value="badgeValue"
              :max="99"
              class="item"
            ></el-badge>
          </div>
          <div class="dropdown-btn">
            <el-dropdown trigger="click" @visible-change="showOrHide">
              <span class="el-dropdown-link">
                <div
                  ref="appTitle"
                  class="tool-btn"
                  :class="{ itemActive: isActive == 'application' }"
                >
                  <i class="iconfont icon-yingyong"></i>
                  <label>应用</label>
                </div>
              </span>
              <el-dropdown-menu ref="searchDropdown" slot="dropdown">
                <div style="width: 312px; max-height: 458px">
                  <searchApp @hideDropdown="hideDropdown"></searchApp>
                </div>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
      <div class="top-right">
        <div class="version">{{ this.version }}</div>
        <div class="item top-tools-select" v-if="isShow">
          <el-select
            v-model="dataSource"
            placeholder="请选择"
            @change="changeApp"
          >
            <el-option
              v-for="item in dataBase"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <el-link
          @click="toOperationManual"
          :underline="false"
          style="color: white"
        >
          <i
            class="iconfont"
            style="font-size: 25px; margin-right: 20px; margin-left: 20px"
            >&#xe6a5;</i
          >
        </el-link>
        <div class="item">
          <el-popover
            placement="top-start"
            title="个人信息"
            width="320"
            trigger="click"
          >
            <div class="userList">
              <el-descriptions :column="1">
                <el-descriptions-item label="用户名">{{
                  userInfo.name
                }}</el-descriptions-item>
                <el-descriptions-item label="手机">{{
                  userInfo.phone
                }}</el-descriptions-item>
                <el-descriptions-item label="部门">
                  <el-select
                    size="mini"
                    v-model="currentInfo.currOrg"
                    placeholder="请选择"
                    @change="changeOrg"
                  >
                    <el-option
                      v-for="item in orgOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-descriptions-item>
                <el-descriptions-item label="身份">
                  <el-select
                    size="mini"
                    v-model="currentInfo.currLeader"
                    placeholder="请选择"
                    @change="changeIdentity"
                  >
                    <el-option
                      v-for="item in idenOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-descriptions-item>
                <el-descriptions-item
                  label="委托人组织"
                  v-if="currentInfo.currLeaderOrg"
                >
                  <el-select
                    size="mini"
                    v-model="currentInfo.currLeaderOrg"
                    placeholder="请选择"
                    @change="changeLeaderOrg"
                  >
                    <el-option
                      v-for="item in leaderOrgOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-descriptions-item>
              </el-descriptions>
              <ul class="operate">
                <li @click="downPrint">
                  <span class="el-icon-download"></span><span>打印控件</span>
                </li>
                <li @click="setUserInfo">
                  <span class="el-icon-setting"></span><span>账号设置</span>
                </li>
                <li @click="signOut">
                  <span class="el-icon-circle-close"></span
                  ><span>退出登录</span>
                </li>
              </ul>
            </div>
            <div class="avatar" slot="reference">
              <img :src="circleUrl" alt="" v-if="circleUrl" />
              <span v-else class="text">{{ userName }}</span>
            </div>
          </el-popover>
        </div>
      </div>
    </div>
    <div class="h100" v-if="routerType != 'menu'">
      <router-view :key="$route.fullPath"></router-view>
    </div>
    <navContent :navConfig="navConfig" v-else>
      <router-view :key="$route.fullPath"></router-view>
    </navContent>
  </div>
</template>

<script>
import { connectWebsocket, closeWebsocket } from "@/utils/webSocket.js";
import searchApp from "./searchApp.vue";
import { signOut } from "@/api/systemManagement/userManagement.js";
import { getVersionApi, downloadPrintSoftware } from "@/api/common.js";
import {
  getConfigDetailList, // 获取配置信息
} from "@/api/systemManagement/configManagement.js";
import { getAddressAfter } from "@/api/orderManagement/spotCheck.js";
export default {
  name: "Home",
  props: [],
  components: {
    searchApp,
  },
  beforeDestroy() {
    closeWebsocket(); //手动关闭websocket连接
  },
  async created() {
    this.getUserInfo();
    this.setHeader();
    this.webSocketControl();
  },
  beforeMount() {},
  mounted() {
    this.init();
  },
  data() {
    return {
      badgeValue: localStorage.getItem("workStationUndo"),
      isActive: "", //sessionStorage.getItem("currentType")? sessionStorage.getItem("currentType"): "workBench",
      tooBtn: [
        {
          icon: "iconfont icon-gongzuotai",
          name: "工作台",
          meta: "workBench",
        },
        {
          icon: "iconfont icon-daiban",
          name: "待办",
          meta: "undo",
        },
      ],
      version: "",
      userInfo: this.$store.getters.mineUserInfo || "",
      currentInfo: this.$store.getters.currentInfo,
      userName: this.$store.getters.userName || "",
      isShow: true,
      content: "",
      routerType: "",
      orgOptions: this.$store.getters.orgList || [],
      idenOptions: this.$store.getters.idenList || [],
      leaderOrgOptions: this.$store.getters.leaderOrgList || [],
      value: "",
      topDescribe: {
        title: "设备资产管理系统",
        logoSrc: require("../assets/img/logo_white.png"),
        navData: {
          navList: [],
          //默认路径
          activeChanel: "/workStation",
        },
      },

      circleUrl: this.$store.getters.avatarUrl,
      // userName: "你好，张三",
      dataBase: this.$store.getters.appListData,
      dataSource: this.$store.getters.currentInfo.currDs || "",
      navConfig: {
        firstNav: {
          navData: {
            navList: [],
            itemName: "",
            logoSrc: "",
          },
        },
        secondNavConfig: {
          //navList: this.$store.getters["currentSecondNav"]("configManagement")
          navList: [],
        },
      },
      appCode: "",
    };
  },
  computed: {
    notYueGang() {
      let appCode = this.$store.getters.currentAppInfo.appCode;
      return !["yggs"].includes(appCode);
    },
  },
  watch: {
    isActive: {
      handler(val, oldVal) {
        //sessionStorage.setItem("currentType", val);
      },
    },
    $route: {
      handler(val, oldval) {
        let appCode =
          this.$router.currentRoute.meta.parentCode ||
          this.$router.currentRoute.meta.type;
        if (appCode == "systemManagement" || appCode == "standardManagement") {
          this.isShow = false;
        } else {
          this.isShow = true;
        }
        if (appCode == "UserInfo" || appCode == "workStation") {
          this.routerType = "";
        } else {
          this.routerType = "menu";
        }
        this.getNavData();
      },
      // 深度观察监听
      deep: true,
    },
    dataSource: {
      handler(val, oldval) {
        this.$store.getters.setSystemCode(val);
      },
    },
  },
  methods: {
    init() {
      this.appCode =
        this.$router.currentRoute.meta.parentCode ||
        this.$router.currentRoute.meta.type;
      if (this.appCode == "upComingCenter") {
        this.isActive = "undo";
      } else if (this.appCode == "workStation") {
        this.isActive = "workBench";
      }
    },
    webSocketControl() {
      // 防止用户多次连续点击发起请求，所以要先关闭上次的ws请求。
      let hosts =
        process.env.VUE_APP_BASEURL === "/api"
          ? "http://10.11.228.110:30001"
          : process.env.VUE_APP_BASEURL;
      let wss = "wss";
      let protocol = hosts.split(":")[0];
      if (protocol === "http") {
        wss = "ws";
      }
      let host = hosts.replace(/^https?\:\/\//i, "");
      let currentDept = this.$store.getters.userInfo.currDs;
      let currentUser = this.$store.getters.userInfo.account;
      let websockurl =
        "" +
        wss +
        "://" +
        host +
        "/eam-service-order/websocket/" +
        currentDept +
        "/" +
        currentUser;
      //let webSocketUrl = 'ws://10.11.228.110:30001/eam-service-order/websocket/krzhoujun'
      connectWebsocket(
        // 测试地址
        websockurl,
        // 传递给后台的数据
        {},
        // 成功拿到后台返回的数据的回调函数
        (data) => {
          //console.log('成功的回调函数, 接收到的data数据： ', data)
          let badgeValue = 0;
          //data = {}的情况
          if (Object.keys(data).length == 0) {
            badgeValue = 0;
          } else {
            //data !={}的情况
            let datas = JSON.parse(data);
            if (datas.data && datas.data.length > 0) {
              badgeValue = datas.data[0].total;
            } else {
              badgeValue = 0;
            }
          }
          this.badgeValue = badgeValue;
        },
        // websocket连接失败的回调函数
        () => {
          // console.log('失败的回调函数')
        }
      );
    },
    getUserInfo() {
      if (!localStorage.getItem("version")) {
        this.getVersion();
      } else {
        this.version = localStorage.getItem("version");
      }
      this.getNavData();
    },
    setHeader() {
      let appCode =
        this.$router.currentRoute.meta.parentCode ||
        this.$router.currentRoute.meta.type;
      if (appCode == "systemManagement" || appCode == "standardManagement") {
        this.isShow = false;
      } else {
        this.isShow = true;
      }
      if (appCode == "UserInfo" || appCode == "workStation") {
        this.routerType = "";
      } else {
        this.routerType = "menu";
      }
    },
    //获取菜单数据
    getNavData() {
      let firstData = [];
      let secondData = [];
      let navName = "";
      let navImg = "";
      let matched = this.$route.matched;
      //设置一级菜单
      if (matched.length > 1) {
        let firstNavName = this.$router.currentRoute.meta.parentCode;
        // let moduleInfo = localStorage.getItem("moduleInfo")
        // let firstNavName = moduleInfo.parentCode;

        let navObj = this.$store.getters.getMenuPicture(firstNavName);
        let { name, imgSrc } = navObj;
        this.navConfig.firstNav.navData.itemName = name;
        this.navConfig.firstNav.navData.logoSrc = imgSrc;
        firstData = this.$store.state.user.allAuth.firstNav[firstNavName] || []; //获取一级菜单数据
      } else {
        this.navConfig.firstNav.navData.navList = [];
      }
      //设置二级菜单
      let secondName = this.$router.currentRoute.meta.code;
      secondData = this.$store.state.user.allAuth.secondNav[secondName] || [];
      this.navConfig.firstNav.navData.navList = firstData;
      this.navConfig.secondNavConfig.navList = secondData;
    },
    hideDropdown(val) {
      let searchDropdown = this.$refs.searchDropdown;
      searchDropdown.showPopper = false;
      this.isActive = "";
    },
    showOrHide(val) {
      if (val) {
        this.isActive = "application";
      } else {
        switch (this.appCode) {
          case "workStation":
            this.isActive = "workBench";
            break;
          case "upComingCenter":
            this.isActive = "undo";
            break;
          default:
            this.isActive = "";
            break;
        }
      }
    },
    goUndoCenter() {
      let { href } = this.$router.resolve({
        path: "/upComingCenter/upComing",
        // params: {
        //   name: data.name,
        //   //logoSrc: data.logoSrc,
        // },
      });
      this.$utils.setCurrentInfo();
      window.open(href, "_blank");
    },
    gotoIndex(item) {
      //sessionStorage.setItem("currentType", item.meta);

      if (item && item.meta == "workBench") {
        this.isActive = item.meta;
        this.$router.push({
          path: "/workStation",
        });
      }
      if (item && item.meta == "undo") {
        this.isActive = item.meta;
        this.$router.push({
          path: "/upComingCenter/upComing",
        });
      }

      //  let { href } = this.$router.resolve({
      //   path: "/workStation"
      // });
      // window.open(href, "_blank");
    },
    //切换应用，刷新浏览器
    changeApp(val) {
      this.$store.commit("SET_CURRDS", val);
      location.reload();
    },
    //切换组织
    changeOrg(val) {
      this.$store.commit("SET_CURRORG", val);
      location.reload();
    },
    //切换身份
    changeIdentity(val) {
      this.$store.commit("SET_CURRIDEN", val);
      location.reload();
    },
    //切换委托人组织
    changeLeaderOrg(val) {
      this.$store.commit("SET_CURRLEADERORG", val);
      location.reload();
    },
    //设置用户信息
    setUserInfo() {
      this.$router.push({
        path: "/userInfo",
      });
    },
    //下载打印控件
    async downPrint() {
      const res = await downloadPrintSoftware();
      let blob = res;
      let reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        let a = document.createElement("a");
        document.body.appendChild(a);
        a.href = e.target.result;
        a.download = "AIOPrint.zip";
        a.click(); //点击触发下载
        window.URL.revokeObjectURL(url); //下载完成进行释放
        document.body.removeChild(a);
      };
    },
    //获取版本信息
    getVersion() {
      const data = {
        classifyCode: "common",
        code: "version",
      };
      getVersionApi(data).then((res) => {
        this.version = res.data.configDetailList[0].value || "";
        localStorage.setItem(
          "version",
          res.data.configDetailList[0].value || ""
        );
      });
    },
    //登出
    async signOut() {
      await signOut();
      this.$utils.clearUserInfo();
      await this.$store.dispatch("GetUserInfo");
    },
    // 操作手册
    toOperationManual() {
      let href = "";
      // 操作手册配置id
      let configId = "1505076693788921856";
      getConfigDetailList({ configId }).then((res) => {
        res.data.map((i) => {
          if (i.key == "url") {
            href = i.value;
          }
        });
        window.open(href, "_blank");
      });
    },
    //去往工程信息化管理平台
    goInfoManage() {
      let param = {
        classifyCode: "common",
        code: "info_manage_url",
      };
      getAddressAfter(param)
        .then((res) => {
          if (res.code == 200) {
            let currentData = res.data ? res.data.configDetailList : [];
            if (currentData.length > 0) {
              let href = currentData[0].value;
              window.open(href, "_blank");
            }
          }
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
  },
};
</script>

<style lang="less" scoped>
#main {
  height: 100%;

  .topContent {
    height: 60px;
    background-color: rgb(6, 88, 203);
    color: #ffffff;
    display: flex;
    flex-flow: wrap nowrap;
    justify-content: space-between;
    // background-image:url("../assets/装饰框.png");
    // background-repeat:no-repeat;/*图片不重复*/
    // background-size:80% 100%;
  }

  .sysName {
    //width: 649px;
    display: flex;
    align-items: center;
    height: 100%;
    padding-right: 56px;
    font-size: 34px;
    background: linear-gradient(175deg, rgb(6, 88, 203), #00e1ff);
    clip-path: polygon(0% 0%, 100% 0%, 93% 100%, 0% 100%);
  }

  .top-logo {
    display: flex;
    align-items: center;
    height: 100%;
    min-width: 220px;
    text-align: left;

    .divider {
      font-size: 20px;
      font-weight: 1;
      line-height: 20px;
      color: #f5f5f5;
    }

    .title-top {
      font-size: 19px;
      font-weight: 500;
      cursor: pointer;
    }

    .title-bottom {
      font-size: 15px;
      font-weight: 500;
    }
  }

  .top-logo :hover {
    //cursor: pointer;
  }

  .top-logo img {
    padding: 12px 20px;
    //padding-right: 20px;
    height: 34px;
  }

  .top-logo label {
    padding-left: 20px;
    font-size: 24px;
    line-height: 100%;
  }

  .itemActive {
    background: rgb(0, 123, 248);
    height: 100%;
  }

  /deep/.tool-btn {
    //padding-left: 41px;
    color: #fff;
    //margin-left: 41px;
    height: 60px;
    padding: 0px 18px;
    line-height: 60px;

    i {
      font-size: 18px;
      line-height: 100%;
    }

    label {
      padding-left: 4px;
      font-size: 16px;
      line-height: 100%;
      cursor: pointer;
    }
  }

  .top-center {
    display: flex;
    align-items: center;
    padding-left: 56px;

    .tool-btn {
      //padding-left: 41px;
      //margin-left: 41px;
      height: 60px;
      padding: 0 18px;
      line-height: 60px;
    }

    i {
      font-size: 18px;
      line-height: 100%;
    }

    label {
      padding-left: 4px;
      font-size: 16px;
      line-height: 100%;
      cursor: pointer;
    }
  }

  .top-right {
    display: flex;
    flex-flow: wrap nowrap;
    font-size: 16px;
    justify-items: center;
    align-items: center;
    color: #ffffff;
    padding-right: 20px;

    .item + .item {
      margin-left: 20px;
      // flex: 1;
    }

    .userName {
      width: 150px;
      text-align: left;
    }

    .tool-btn {
      //padding-left: 41px;
      //margin-left: 41px;
      height: 60px;
      padding: 0 18px;
      line-height: 60px;
    }

    i {
      font-size: 18px;
      line-height: 100%;
    }

    label {
      padding-left: 4px;
      font-size: 16px;
      line-height: 100%;
      cursor: pointer;
    }
  }

  .version {
    height: 34px;
    line-height: 34px;
    margin: 0 21px;
    background: none !important;
    color: #fff !important;
    font-size: 16px;
  }

  .top-tools-select {
    /deep/.el-input__inner {
      height: 30px;
      line-height: 30px;
      background: none !important;
      color: #fff !important;
      width: 130px !important;
      font-size: 14px;
      border-radius: 40px;
    }

    /deep/.el-input__icon {
      line-height: 30px;
    }
  }
}

.userList {
  .operate {
    border-top: 1px solid #e6e6e6;

    li {
      height: 30px;
      line-height: 30px;
      padding-left: 5px;
    }

    li:hover {
      background-color: #eaf2ff;
      color: #2c77f4;
      cursor: pointer;
    }
  }
}

.avatar {
  width: 40px;
  height: 40px;
  background: #c7ddff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;

  img {
    width: 40px;
    height: 40px;
    overflow: hidden;
    border-radius: 50%;
  }

  .text {
    font-size: 18px;
    font-weight: 400;
    color: #ffffff;
  }
}

/deep/.el-badge {
  position: relative;
  vertical-align: inherit;
  display: inline-block;
  top: -6px;
  left: 2px;
}

/deep/.el-badge__content {
  background-color: #f56c6c;
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  text-align: center;
  white-space: nowrap;
  border: none;
}
</style>
